package com.blame.chatRobot.controller;

import com.blame.chatRobot.entity.ChatInfo;
import com.blame.chatRobot.entity.MessageVo;
import com.blame.chatRobot.repository.MemoryChatHistoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
//import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 何彦声st
 * Date: 2025-08-29
 * Time:
 */

@RestController
@RequestMapping("/chat")
public class ChatRobotController {

    private final ChatClient chatClient;

    @Autowired
    private MemoryChatHistoryRepository memoryChatHistoryRepository;

    @Autowired
    private ChatMemory chatMemory;

    @Autowired
    private OpenAiChatModel openAiChatModel;

    public ChatRobotController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @RequestMapping(value = "/stream",produces = "text/html;charset=utf-8")
    public Flux<String> stream(@RequestParam String prompt,String chatId){

        if (prompt == null || prompt.trim().isEmpty()) {
            return Flux.just(" message 参数不能为空！");
        }
        memoryChatHistoryRepository.save(prompt, chatId);
        return chatClient.prompt()
                .user(prompt)
                .advisors(spec -> spec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content();
    }

//    获得会话列表
@RequestMapping("/getChatIds")
    public List<ChatInfo> getChatIds(){
        return memoryChatHistoryRepository.getChats();
    }



//  活得会话记录
@RequestMapping("/getChatHistory")
    public List<MessageVo> getChatHistory(String chatId){
        List<Message> messages = chatMemory.get(chatId, 20);
        return messages.stream().map(MessageVo::new).collect(Collectors.toList());
    }

//    删除会话记录
@RequestMapping("/deleteChat")
    public boolean clearChat(String chatId){
        try {
            memoryChatHistoryRepository.clearByChatId(chatId);
            chatMemory.clear(chatId);
        }catch (Exception e){
            return false;
        }
        return true;
    }

}
